<template>
  <div >
    <div  v-loading="loading"   v-show="indexShow"
     element-loading-text="加载中。。。">
      <el-card>
        <el-form ref='QueryForm' :model='QueryForm'  size='mini'  label-position="top">
          <el-row :gutter="10">
            <el-col  :lg="4" :md="6">
              <el-form-item label='应用编号'  prop='appId'>
                <el-select v-model="QueryForm.appId" filterable placeholder="请选择应用编号" >
                  <el-option
                  v-for="item in appId"
                  :key="item.AppNum"
                  :label="item.AppNum+'-'+item.AppName"
                  :value="item.AppNum"
                  :disabled="item.disabled">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col  :lg="2" :md="3" class="searchBtnMarginTop">
              <el-button type='primary' size='mini' icon='el-icon-search' @click="queryMenuModel">查询</el-button>
            </el-col>
            <el-col  :lg="2" :md="3" class="searchBtnMarginTop">
              <el-button type='warning' size='mini' icon='el-icon-refresh'
              @click="resetForm('QueryForm')">重置</el-button>
            </el-col>
          </el-row>
        </el-form>
      </el-card>
      <el-card style="margin-top:10px;" >
        <el-row>
          <el-col :lg="2" :md="3">
            <el-button type="primary" icon='el-icon-plus' size="mini" @click="clickAdd" v-if="btnPermission('Button_Menu_Add')">新增</el-button>
          </el-col>
          <el-col :lg="2" :md="3">
            <el-button type="primary" icon='el-icon-edit' :disabled="!isDisabledDel" size="mini" @click="clickUpdate" v-if="btnPermission('Button_Menu_Add')">修改</el-button>
          </el-col>
          <el-col :lg="2" :md="3">
            <el-button type="danger" icon='el-icon-delete' :disabled="!isDisabledDel" size="mini" @click="delBut" v-if="btnPermission('Button_Menu_Edit')">删除</el-button>
          </el-col>
          <el-col :lg="3" :md="3">
            <el-dropdown size="mini"   trigger="click" @command="itemClick" >
              <el-button type="primary" size="mini" :disabled="!isPub" v-if="btnPermission('Button_Menu_Release')">
                    发布<i class="el-icon-arrow-down el-icon--right"></i>
              </el-button>
              <el-dropdown-menu slot="dropdown"  >
                <el-dropdown-item command="0">按设备发布</el-dropdown-item>
                <!-- <el-dropdown-item command="1">按分组发布</el-dropdown-item> -->
                <el-dropdown-item command="2">按机构发布</el-dropdown-item>
                <!-- <el-dropdown-item command="3">按设备分类发布</el-dropdown-item> -->
              </el-dropdown-menu>
            </el-dropdown>
          </el-col>
        </el-row>
        <el-table  ref="menuModelList" :data='menuModelList' border style="min-height:390px"
          class="tableMarginTop"
          header-row-class-name="tableHeaderClass"
          @select-all="selectAll"
          @selection-change="selectList">
            <el-table-column type="selection" width="40px"></el-table-column>
            <el-table-column prop='appnum' label='应用编号' min-width='107px'></el-table-column>
            <el-table-column prop='menuviewnum' label='菜单视图编号' min-width='107px'></el-table-column>
            <el-table-column prop='menuviewname' label='菜单视图名称'  min-width='107px'></el-table-column>
            <el-table-column prop='sortnum' label='排序号' min-width='107px'></el-table-column>
            <el-table-column prop='mainbranch' label='维护机构' min-width='107px'  ></el-table-column>
            <el-table-column prop='mainuser' label='维护用户' min-width='107px'></el-table-column>
            <el-table-column prop='maindate' label='维护日期' :formatter="dateFormat"  min-width='107px'></el-table-column>
            <el-table-column prop='maintime' label='维护时间' :formatter="tableDateFormat" min-width='107px'  ></el-table-column>
            <el-table-column  label="菜单预览" align="center" fixed="right" width="80">
                <template slot-scope="scope">
                    <el-button type="text" size="mini"  v-if="scope.row.appnum == 'SS' ||scope.row.appnum == 'ATM'"
                   @click="dialogDetail(scope)">预览</el-button>
                </template>
            </el-table-column>
        </el-table>
        <div  style="text-align:right;margin-top:10px">
          <el-pagination background
              @current-change="handleCurrentChange"
              :current-page="currentPage"
              :page-size="10"
              layout="total, prev, pager, next, jumper"
              :total="total">
          </el-pagination>
        </div>
      </el-card>
      <el-dialog title="按设备发布" :visible.sync="devPub" width="770px" @open="devOpen" :close-on-click-modal=false>
        <el-card v-loading="loadingDev">
        <el-form inline :data="modelDevPub" size="mini">
          <el-form-item label="机构:">
            <el-select v-model="modelDevPub.branchNo" filterable placeholder="请选择所属机构号" >
              <el-option
              v-for="item in brnoList"
              :key="item.value"
              :label="item.orgno+'-'+item.cname"
              :value="item.orgno">
              </el-option>
              </el-select>
          </el-form-item>
          <el-button type="primary" size="mini" @click="queryDev">查询</el-button>
        </el-form>
          <el-table  ref="devList" :data="devList" max-height="300"
          @selection-change="releaseTableChangeHandel"
              style="margin-top:5px;border:1px solid #ebeef5;border-radius:3px;" >
              <el-table-column type="selection"></el-table-column>
              <el-table-column prop='devicenum' label='设备编号' min-width='107px'></el-table-column>
              <el-table-column prop='devicetype' label='设备类型' min-width='107px'></el-table-column>
              <el-table-column prop='ascrbranchname' label='所在网点' min-width='107px'></el-table-column>
              <el-table-column prop='devicemodel' label='设备型号' min-width='107px'></el-table-column>
          </el-table>
          <div class="box" style="text-align:right;margin-top:10px">
            <el-pagination background
              @current-change="handleCurrentChangeDev"
              :current-page="currentPageDev"
              :page-size="pageSizeDev"
              layout="total, prev, pager, next, jumper"
              :total="totalDev">
            </el-pagination>
          </div>
        </el-card>
        <span slot="footer" class="dialog-footer">
          <el-button @click="devPub = false" size="mini">取 消</el-button>
          <el-button type="primary" @click="releaseSubmit('dev')" size="mini">确 定</el-button>
        </span>
      </el-dialog>
      <el-dialog title="按机构分组发布" :visible.sync="areaPub" width="400px" @open="openGroup" @close="modelAreaPub.areaList=''">
        <el-card v-loading="loadingGroup">
        <el-form inline :data="modelAreaPub" size="mini">
          <el-row>
            <el-col :span="24">
            <el-form-item label="机构分组:">
              <el-select v-model="modelAreaPub.areaList"
                    placeholder="请选择分组">
                     <el-option
                        v-for="item in areaList"
                        :key="item.branchAreaId"
                        :label="item.branchgroupname"
                        :value="item.branchgroupid">
                    </el-option>
              </el-select>
            </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        </el-card>
        <span slot="footer" class="dialog-footer">
          <el-button @click="areaPub = false" size="mini">取 消</el-button>
          <el-button type="primary" @click="releaseSubmit('dis')" size="mini">确 定</el-button>
        </span>
      </el-dialog>
      <el-dialog title="按机构发布" :visible.sync="branchPub" width="400px" @open='brnoOpen' @close="modelBranchPub.branchNo=[]">
        <el-card style="overflow:visible;max-height:400px;overflow:auto;" v-loading="loadingBrno">
          <el-form inline :data="modelBranchPub" size="mini">
            <el-form-item label="机构:">
              <select-tree v-model="modelBranchPub.branchNo" style="width:250px;"
                        :props='{id:"orgno",label: "cname",children: "children"}'
                        :tree-data="brnoList1" :node-key="'orgno'" ></select-tree>
            </el-form-item>
          </el-form>
        </el-card>
        <span slot="footer" class="dialog-footer">
          <el-button @click="branchPub = false" size="mini">取 消</el-button>
          <el-button type="primary" @click="releaseSubmit('branch')" size="mini">确 定</el-button>
        </span>
      </el-dialog>
      <el-dialog title="按设备分类发布" :visible.sync="devShortPub" width="400px" @open='openSort' @close="devShortForm.devShort=[]">
        <el-card style="overflow:visible" v-loading="loadingSort">
          <el-form inline :data="devShortForm" size="mini">
            <el-row>
            <el-col :span="24">
            <el-form-item label="设备分类:">
             <el-select v-model="devShortForm.devShort" multiple placeholder="请选择设备分类" >
                <el-option
                v-for="item in devSort"
                :key="item.AssortmentId"
                :label="item.AssortmentName"
                :value="item.AssortmentId"
                :disabled="item.disabled">
                </el-option>
              </el-select>
            </el-form-item>
            </el-col>
            </el-row>
          </el-form>
        </el-card>
        <span slot="footer" class="dialog-footer">
          <el-button @click="devShortPub = false" size="mini">取 消</el-button>
          <el-button type="primary" @click="releaseSubmit('devSort')" size="mini">确 定</el-button>
        </span>
      </el-dialog>
    </div>
    <keep-alive>
      <component :is='dialogList.menuModelAdd' :option='dialogOptions' @refreshTable="queryMenuModel"></component>
    </keep-alive>
    <keep-alive>
       <component :is='dialogList.menuModelDetail' :option='dialogOptionsDetail'></component>
    </keep-alive>
  </div>
</template>


<script>
import menuModelAdd from "./dialog/menuModelAdd";
import menuModelDetail from "./dialog/menuModelDetail";
import request from "@/common/utils/request";
import branchList from "@/message/shared/branch-list"; //机构号
import getGlobalParams from "@/common/utils/getGlobalParams";
import appQuery from "@/message/shared/appquery";//应用编号
import delMenuModel from "@/message/resourceManage/menu/menuModel/menu-model-del";
import releaseIns from "@/message/resourceManage/menu/menuModel/menu-model-publish";
import queryAppId from "@/message/resourceManage/menu/menuModel/menu-model-query";
import branchGroup from "@/message/branchManage/branchGroupMgr/branch-group-mgr";
import toolBox from "@/common/utils/toolBox";
import devInfo from "@/message/deviceInfoManage/devInfo/dev-info-query";
import devShortInfo from "@/message/deviceInfoManage/short/dev-short-query";
import selectTree from "@/components/selectTree2/";
export default {
  components: { selectTree },
  data() {
    return {
      currentRow:[],//当前表格选中数据
      QueryForm: {
        //查询表单
        appId: ""
      },
      appId: [], //应用编号下拉框
      modelDevPub: {
        branchNo: ""
      },
      loadingSort: false,
      loadingBrno: false,
      loadingGroup: false,
      loadingDev: false,
      devList: [],
      props: {
        label: "cname",
        children: "children"
      },
      total: undefined,
      areaList: [], //分组下拉框数据
      modelAreaPub: { areaList: "" },
      brnoList1: [],
      menuModelList: [],
      releaseSelection: [],
      brnoList: [],
      devLists: [],
      devSort: [],
      loading: false,
      devPub: false,
      areaPub: false,
      branchPub: false,
      devShortPub: false,
      isDisabledDel: false,
      isPub: false,
      dialogList: { menuModelAdd, menuModelDetail },
      dialogOptions: { isShow: false },
      dialogOptionsDetail: { isShow: false, menuList: [] },
      branchNo: [],
      modelBranchPub: {
        branchNo: []
      },
      devShortForm: {
        devShort: []
      },
      currentPage: 1,
      pageSize: undefined,
      currentPageDev: 1,
      pageSizeDev: undefined,
      totalDev: 0,
      currentPageGroup: 0,
      menu_Model_Id: undefined,
      menu_Model_Id_pub: undefined,
      enum: {
        "0": "否",
        "1": "是"
      }
    };
  },
  created() {
    this.pageSize = getGlobalParams.get("PageSize");
    this.pageSizeDev = getGlobalParams.get("PageSize");
    this.queryAppId();
    this.queryMenuModel();
  },
  computed: {
    indexShow() {
      return !this.dialogOptionsDetail.isShow;
    }
  },
  methods: {
    queryAppId() {
      let resBody1 = new appQuery();
      resBody1.data.UserNum = this.$store.getters.UserNum;
      request(resBody1)
        .then(response => {
          this.loading = false;
          if (response.APP_HEAD.ReturnCode === "000000") {
            this.loadingSort = false;
            this.appId = response.RspInfo.Result;
          } else {
            this.loadingSort = false;
            this.$message({
              type: "warning",
              message: SYS_HEAD.ReturnMessage
            });
          }
        })
        .catch(error => {
          this.loadingSort = false;
          //   this.logger.log("fail", error);
        });
    },
    clickAdd() {
      this.dialogOptions.isShow = true;
      this.dialogOptions.title = "新增";
      this.dialogOptions.mark = "1";
      this.dialogOptions.isDisabled = false;
    },
    clickUpdate() {
      this.dialogOptions.isShow = true;
      this.dialogOptions.title = "修改";
      this.dialogOptions.mark = "2";
      this.dialogOptions.isDisabled = true;
      this.dialogOptions.currentRow = this.currentRow;
    },
    resetForm() {
      this.$refs.QueryForm.resetFields();
    },
    openGroup() {
      this.initSpinnerDataList();
    },
    openSort() {
      this.loadingSort = true;
      let resBody1 = new devShortInfo();
      resBody1.data.devAssortmentName = "";
      resBody1.QueryPageNo = 0;
      resBody1.QueryRowNum = 99999;
      request(resBody1)
        .then(response => {
          this.loading = false;
          if (response.SYS_HEAD.ReturnCode === "000000") {
            this.loadingSort = false;
            this.devSort = response.RspInfo.devAssortmentList;
          } else {
            this.loadingSort = false;
            this.$message({
              type: "warning",
              message: SYS_HEAD.ReturnMessage
            });
          }
        })
        .catch(error => {
          this.loadingSort = false;
          //   this.logger.log("fail", error);
        });
    },
    dialogDetail(value) {
      //预览
      this.dialogOptionsDetail.isShow = true;
      this.dialogOptionsDetail.menuList = value.row;
    },
    releaseTableChangeHandel(val) {
      //按设备发布表格
      this.releaseSelection = val;
    },
    async releaseSubmit(type) {
      //发布得事件
      let resBody = new releaseIns();
      // resBody.data.devId = ""
      this.currentRow
      resBody.data.AppNum = this.currentRow.appnum;
      resBody.data.MenuViewNum = this.currentRow.menuviewnum;
      if (type == "dev") {
        var temp = [];
        for (var i = 0; i < this.releaseSelection.length; i++) {
          temp.push(this.releaseSelection[i].devicenum);
        }
        this.devPub = false;
        resBody.data.publicType = "1"; //按设备发布标记
        resBody.data.publicTypeVal = temp.join(",");
      } else if (type == "branch") {
        this.branchPub = false;
        resBody.data.publicType = "2"; //按机构发布标记
        resBody.data.publicTypeVal = this.modelBranchPub.branchNo.join(","); // this.modelDevPub.branchNo;
      } else if (type == "dis") {
        this.areaPub = false;
        resBody.data.publicType = "3"; //按分组发布标记
        resBody.data.publicTypeVal = this.modelAreaPub.areaList; //.join(","); //这里是区域号  还没有查询的请求
      } else if (type == "devSort") {
        this.devShortPub = false;
        resBody.data.publicType = "4"; //按设备分类发布标记
        resBody.data.publicTypeVal = this.devShortForm.devShort.join(","); //这里是区域号  还没有查询的请求
      }
      let response = await request(resBody);
      if (response.SYS_HEAD.ReturnCode == "000000") {
        this.$message({
          type: "success",
          message: "提交成功!"
        });
        this.queryMenuModel();
      } else {
        this.$message({
          type: "error",
          message:
            "请求失败，错误码:" +
            response.SYS_HEAD.ReturnCode +
            "，错误信息：" +
            response.SYS_HEAD.ReturnMessage
        });
      }
    },
    //分组下拉框初始化
    initSpinnerDataList() {
      this.loadingGroup = true;
      let resBody = new branchGroup();
      resBody.data.BranchGroupNum = ""; //this.formInline.BranchGroupNum;
      resBody.data.BranchGroupName = ""; // this.formInline.BranchGroupName;
      resBody.data.LegalPersonNum = this.$store.getters.LegalPersonNum;
      resBody.data.OperType = "Q"; // 操作类型
      // 查询公共参数
      resBody.data.length = 99999;
      resBody.data.draw = "2";
      resBody.data.start = 0;
      request(resBody)
        .then(response => {
          this.loadingGroup = false;
          if (response.SYS_HEAD.ReturnCode === "000000") {
            this.areaList = response.RspInfo.pageList || [];
          } else {
            this.$message({
              type: "error",
              message: response.SYS_HEAD.ReturnMessage
            });
          }
        })
        .catch(error => {
          this.loadingGroup = false;
          //   this.logger.log("fail", error);
        });
    },
    dateFormat(row, column) {
      //枚举设备形式
      return toolBox.timeFormat2Date(row[column.property]);
    },
    tableDateFormat(row, column) {
      return toolBox.timeFormat2Time(row[column.property]);
    },
    delBut() {
      this.$confirm("此操作将永久删除该菜单, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.menuModelDel();
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    menuModelDel() {
      //删除菜单
      this.loading = true;
      let resBody = new delMenuModel();
      resBody.data.AppNum = this.currentRow.appnum;
      resBody.data.MenuViewNum = this.currentRow.menuviewnum;
      request(resBody)
        .then(response => {
          if (response.APP_HEAD.ReturnCode === "000000") {
            this.loading = false;
            this.$message({
              type: "success",
              message: "菜单视图删除成功！"
            });
            this.queryMenuModel();
          } else {
            this.loading = false;
            this.$message({
              type: "error",
              message: response.SYS_HEAD.ReturnMessage
            });
          }
        })
        .catch(error => {
          this.loading = false;
          console.log(error);
        });
    },
    queryMenuModel() {
      //查询菜单
      this.isPub = false;
      this.loading = true;
      let resBody = new queryAppId();
      resBody.data.AppNum = this.QueryForm.appId;
      resBody.data.length = this.pageSize;
      resBody.data.start =(this.currentPage-1)*this.pageSize;
      request(resBody)
        .then(response => {
          if (response.APP_HEAD.ReturnCode === "000000") {
            this.loading = false;
            if (response.RspInfo) {
              this.menuModelList = response.RspInfo.pageList;
              this.total = response.RspInfo.recordsTotal;
            } else {
              this.loading = false;
              this.$message({
                type: "warning",
                message: "没有满足条件得记录!"
              });
            }
          } else {
            this.loading = false;
            this.$message({
              type: "error",
              message:
                "请求失败，错误码:" +
                response.SYS_HEAD.ReturnCode +
                "，错误信息：" +
                response.SYS_HEAD.ReturnMessage
            });
          }
        })
        .catch(error => {
          this.loading = false;
          console.log(error);
        });
    },
    handleCurrentChange(val) { //分页事件
      this.currentPage = val;
      this.queryMenuModel()
    },
    handleCurrentChangeDev(val) { //按设备发布表格事件
      this.currentPageDev = val;
      this.queryDev();
    },
    brnoOpen() {
      //按 机构发布初始化下拉列表
      this.loadingBrno = true;
      let resBody = new branchList();
      resBody.data.orgno = this.$store.getters.BranchNum;
      request(resBody)
        .then(response => {
          let brnoList1 = response.RspInfo.Result || [];
          this.brnoList1 = toolBox.formatTreeData(
            brnoList1,
            "orgno",
            "superno"
          );
          this.loadingBrno = false;
        })
        .catch(error => {
          this.loadingBrno = false;
          console.error("查询错误", error);
        });
    },
    devOpen() {
      //按设备发布
      //初始化下拉列表
      this.loadingDev = true;
      let resBody = new branchList();
      resBody.data.orgno = this.$store.getters.BranchNum;
      request(resBody)
        .then(response => {
          this.loadingDev = false;
          this.brnoList = response.RspInfo.Result || [];
          this.brnoList.unshift({ orgno: "", cname: "" });
        })
        .catch(error => {
          this.loadingDev = false;
          console.error("查询错误", error);
        });
      this.queryDev();
    },
    async queryDev() {
      //查询
      this.loadingDev = true;
      this.devList = [];
      let resBody = new devInfo();
      resBody.data.DeviceModel = "";
      resBody.data.DeviceNum = "";
      resBody.data.DeviceState = "";
      resBody.data.AscrBranch = this.modelDevPub.branchNo;
      resBody.data.devNum = "";
      resBody.data.start = (this.currentPageDev - 1) * this.pageSizeDev;
      resBody.data.length = this.pageSizeDev;
      resBody.data.draw = 2; //this.pageSize;
      request(resBody)
        .then(response => {
          if (response.APP_HEAD.ReturnCode === "000000") {
            this.loadingDev = false;
            if (response.RspInfo) {
              this.devList = response.RspInfo.pageList;
            }
          } else {
            this.loadingDev = false;
            this.$message({
              type: "success",
              message: `${response.SYS_HEAD.ReturnMessage}!`
            });
          }
          this.totalDev = response.RspInfo.recordsTotal
            ? response.RspInfo.recordsTotal
            : 0;
        })
        .catch(error => {
          this.loading = false;
          console.log(error);
        });
    },
    selectAll(row) {
      //表格全选
      if (row.length >= 1) {
        this.isDisabledDel = true;
      } else {
        this.isDisabledDel = false;
      }
    },
    selectList(selection) {
      this.currentRow=selection[0];
      //表格选中事件
      //控制按钮是否禁用
      if (selection.length == 1) {
        this.isDisabledDel = true;
        this.isPub = true;
      } else if (selection.length > 1) {
        this.isDisabledDel = true;
        this.isPub = false;
      } else {
        this.isDisabledDel = false;
        this.isPub = false;
      }
    },
    itemClick(val) {
      //发布按钮
      val === "0"
        ? (this.devPub = true)
        : val === "1"
          ? (this.areaPub = true)
          : val === "2" ? (this.branchPub = true) : (this.devShortPub = true);
    }
  }
};
</script>

<style lang="scss" scoped>
</style>
